package com.demo2do.boyle.client.handler.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.handler.OpenIdAuthHandler;
import com.demo2do.boyle.client.service.CustomerService;
import com.demo2do.boyle.common.entity.customer.Customer;

/**
 * 
 * @author Wilson Jason.Y
 */
@Component("openIdAuthHandler")
public class OpenIdAuthHandlerCacheImpl implements OpenIdAuthHandler {

    private static final Logger logger = LoggerFactory.getLogger(OpenIdAuthHandlerCacheImpl.class);

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private CustomerService customerService;
    
    /*
     * (non-Javadoc)
     * @see com.demo2do.boyle.client.handler.OpenIdAuthHandler#authenticate(java.lang.String)
     */
    public Customer authenticate(final String openId) {

        if(openId == null) {
            return null;
        }

        logger.info("authenticate using openId[" + openId +"]");

        Customer customer = null;

        Cache cache = cacheManager.getCache(Constant.CACHE_AUTHENTICATION);
        String cacheKey = Constant.CACHE_ACCOUNT_PREFIX + openId;
        Cache.ValueWrapper valueWrapper = cache.get(cacheKey);

        if(valueWrapper == null) {

            logger.info("customer not found from cache");

            // load customer by open id
            customer = customerService.loadByOpenId(openId);

            // save customer into cache
            if(customer != null) {
                logger.info("save customer into cache");
                cache.put(cacheKey, customer);
            }

        } else {

            customer = (Customer)valueWrapper.get();
            logger.info("successfully retrive customer from cache");

        }

        return customer;
    }

    
	public boolean logout(Customer customer) {
		try {
			// clear database's open id
			String openId = customer.getOpenId();
			if (openId != null) {
				customerService.update(customer.unBindOpenId());
			}

			// clear cache
			Cache cache = cacheManager.getCache(Constant.CACHE_AUTHENTICATION);
			String cacheKey = Constant.CACHE_ACCOUNT_PREFIX + openId;
			cache.evict(cacheKey);

			return true;

		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
		
	}

}
